// sub/user/iron-one/iron-one.js
const app = getApp();
import Toast from '../../../miniprogram/miniprogram_npm/vant-weapp/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navTabList: [],
    tabActive: 0,
    lastActive:0,
    childrenList: [],
    niceList: [],
    isEmpty: false,
    noMore: false,
    tempShopId: '',
    cateringType: '',
    productType: '',
    productTypeValue: '',
    productTypeShow: false,//右上角显示

    firstId:'0',//点击右侧选规格后存下来的左侧分类id
    rangeShow: true,//规格显示
    goodInfo: {},//点击选规格后获取的商品数据
    rangeNum: '1',//弹框内商品的数量
    selectRangeId: '0',//当前点击选择某一个规格的id，关闭规格弹框时清空
    selectRangeName: '',//当前点击选择某一个规格的名称，关闭规格弹框时清空
    shopCarList: [],//购物车列表
    cartShow: false,//购物车下面一块显示隐藏
    cartListShow: 'none',//购物车上面一块列表显示隐藏
    totalCount: '0',//购物车总数量
    totalPrice: '0',//购物车总价格
    heightArr: [],
    containerH: 0,
    contentActive: '',
    conHeight:'',
  },
  onReady: function () {
    this.animation = wx.createAnimation()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    let that = this;
    let scene = event.scene;
    let tempShopId = wx.getStorageSync('tempShopId');//缓存shopId
    let shopInfo = app.getShop();
    if (scene) {
      let tt = scene.split('-');
      if (tt.length > 0) {
        let obj = {};
        tt.forEach(item => {
          obj[item.split('!')[0]] = item.split('!')[1];
        })
        console.log('productType=' + obj.productType + '--cateringType=' + obj.cateringType);
        // 将座位号存入缓存
        if (obj.tid) {
          tempShopId = obj.tid;
          that.setData({
            tempShopId: tempShopId,
            // 外卖类型
            productType: obj.productType,
            //餐饮类型
            cateringType: obj.cateringType
          });
          if (obj.productType == '6' && obj.cateringType == '1') {
            that.setData({
              productTypeValue: '堂食点单',
            })
          } else if (obj.productType == '6' && obj.cateringType == '3') {
            that.setData({
              productTypeValue: '到店自提',
              productType: '6',
              cateringType: obj.cateringType,
            })
          } else {
            that.setData({
              productTypeValue: '外卖点单',
              productType: '6',
              cateringType: obj.cateringType,
            })
          }
          wx.setStorageSync("seatNum-" + that.data.tempShopId, obj.seatNum);
          // 校验本地缓存shopinfo是否有值，如果有值则根据shopid替换shopinfo的数据，如果没值则取地址list第一条数据
          if (shopInfo) {
            // 如果不对等，则调接口覆盖数据，如果对等，则shopinfo不变
            if (tempShopId != shopInfo.id) {
              that.getShopInfo(tempShopId);
            } else {
              that.setData({
                shopInfo: shopInfo
              })
            }
          } else {
            that.getShopInfo(tempShopId);
          }
          wx.setStorageSync('tempShopId', that.data.tempShopId);
        }
      }
    } else {
      that.setData({
        tempShopId: tempShopId,
        shopInfo: app.getShop(),
        productType: '6',
        cateringType: event.cateringType
      });
      if (event.cateringType == '1') {
        that.setData({
          productTypeValue: '扫码堂食',
        })
      } else if (event.cateringType == '2') {
        that.setData({
          productTypeValue: '外卖点单',
        })
      } else {
        that.setData({
          productTypeValue: '到店自提',
        })
      }
    }
  },
  getShopInfo(val) {
    let that = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/newNearest',
      data: {
        mid: val,
        longitude: '112.98626',
        latitude: '28.25591',
        limit: 50,
        centreId: app.globalData.loginCentreId,
        flag: 2//1平台 2商户
      },
      load: 1
    }).then((res) => {
      that.setData({
        shopInfo: res.data.data[0]
      });
      wx.setStorageSync('shopInfo', JSON.stringify(res.data.data[0]));
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getNavTab();
  },


  //获取tab
  getNavTab() {
    let _this = this;
    let user = app.getUser();

    app.requestUrl({
      method: 'GET',
      url: '/wxapi/categoryGoods',
      data: {
        parentid: 0,
        centreId: app.globalData.loginCentreId,
        teamId: app.getShop().id
      },
      load: 1
    }).then((res) => {
      let list = _this.makeTree(res.data.categoryList);
      list.forEach(item =>{
        if(!item.count || item.count == ''){
          item.count = 0;
        };
     });
      _this.setData({
        navTabList: list,
      });
      _this.setHeightArr();
    })
  },
  //处理tab数据
  makeTree(data) {
    let tree = {};
    data.forEach(item => {
      if (item.enabled && (item.status === 1)) {
        tree[item.id] = item;
      }
    });

    data.forEach(item => {
      if (item.enabled && (item.status === 1) && (item.parentid > 0)) {
        let parent = tree[item.parentid];

        if (parent) {
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(item);
        }
      }
    });

    return data.filter(item => (item.parentid === 0) && ((item.enabled && (item.status === 1))));
  },
  selectFirstTab: function (e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    that.setData({
      contentActive: id
    });
  },
  setHeightArr: function () {
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        let windowHeight = (res.windowHeight * (750 / res.windowWidth)); //将高度乘以换算后的该设备的rpx与px的比例
        //console.log(windowHeight) //最后获得转化后得rpx单位的窗口高度
        _this.setData({
          conHeight: windowHeight,
        })
      }
    });
    let query = wx.createSelectorQuery().in(this);
    let heightArr = [];
    let s = 0;
    query.selectAll('.pesticide').boundingClientRect((react) => {
      react.forEach((res) => {
        s += res.height;
        heightArr.push(s)
      });
      this.setData({
        heightArr: heightArr
      })
    });
    query.select('.content').boundingClientRect((res) => {
      // 计算容器高度
      this.setData({
        containerH: res.height
      })
    }).exec();
  },
  onScroll(e) {
    let _this = this;
    let scrollTop = e.detail.scrollTop;
    let scrollArr = _this.data.heightArr;
    if (scrollTop >= scrollArr[scrollArr.length - 1] - (_this.data.containerH/2)) {
      return;
    } else {
      for (let i = 0; i < scrollArr.length; i++) {
        if (scrollTop >= 0 && scrollTop < scrollArr[0]) {
          if (0 != _this.data.lastActive) {
            _this.setData({
              tabActive: 0,
              lastActive:0,
            })
          }
        } else if (scrollTop >= scrollArr[i - 1] && scrollTop < scrollArr[i]) {
          if (i != _this.data.lastActive) {
            _this.setData({
              tabActive: i,
              lastActive: i,
            })
          }
        }
      }
    }
  },
  // 点击右上角打开弹框
  showProductTypeFunction() {
    this.setData({ productTypeShow: true });
  },

  closeProductTypeFunction() {
    this.setData({ productTypeShow: false });
  },
  // 点击选择是堂食还是外卖
  selectProductType(e) {
    let that = this;
    if (e.currentTarget.dataset.cateringtype == '1') {//堂食，进入扫码点单
      // 允许从相机和相册扫码
      wx.scanCode({
        success: (res) => {
          var result = res.result;
          wx.redirectTo({
            url: res.path
          })
        }
      })
    } else if (e.currentTarget.dataset.cateringtype == '2') {//外卖
      that.setData({
        productType: e.currentTarget.dataset.type,
        cateringType: e.currentTarget.dataset.cateringtype,
        productTypeShow: false,
        productTypeValue: '外卖点单',
      });
      // this.getNiceList(false);
      this.toEnclosure(e.currentTarget.dataset.cateringtype);
    } else {
      that.setData({
        productType: e.currentTarget.dataset.type,
        cateringType: e.currentTarget.dataset.cateringtype,
        productTypeShow: false,
        productTypeValue: '到店自提',
      });
      // this.getNiceList(false);
      this.toEnclosure(e.currentTarget.dataset.cateringtype);
    }
  },

  //附近门店
  toEnclosure(cateringtype) {
    wx.redirectTo({
      url: '/subIndex/index/enclosure/enclosure?cateringType=' + cateringtype
    })
  },
  // 显示规格
  showRangeFunction: function (e) {
    this.setData({ rangeShow: false, goodInfo: e.currentTarget.dataset.good,firstId:e.currentTarget.dataset.firstid });
  },
  // 关闭规格
  closeRangeFunction: function () {
    this.setData({ rangeShow: true });
  },
  // 选择规格
  selectRangeFunction: function (e) {
    this.setData({
      selectRangeId: e.currentTarget.dataset.id,
      selectRangeName: e.currentTarget.dataset.name
    })
  },
  // 弹框内商品的加减
  HZL_jian: function () {
    let that = this;
    let rangeNum = that.data.rangeNum;
    rangeNum--;
    if (rangeNum <= 1) {
      rangeNum = 1;
    };
    that.setData({
      rangeNum: rangeNum
    })
  },
  HZL_jia: function () {
    let that = this;
    let rangeNum = that.data.rangeNum;
    rangeNum++;
    that.setData({
      rangeNum: rangeNum
    })
  },
  // 弹框内加入购物车
  addCart: function () {
    let that = this;
    let addCartInfo = {};
    if (that.data.selectRangeId == '0') {
      Toast('请选择规格');
      return;
    } else {
      // 赋值购物车列表里的对象
      addCartInfo.vipprice = that.data.goodInfo.vipprice;
      // 单个价格
      addCartInfo.marketprice = that.data.goodInfo.marketprice;
      addCartInfo.selectRangeId = that.data.selectRangeId;
      addCartInfo.selectRangeName = that.data.selectRangeName;
      addCartInfo.count = that.data.rangeNum;
      addCartInfo.productId = that.data.goodInfo.id;
      addCartInfo.productName = that.data.goodInfo.title;
      addCartInfo.firstId = that.data.firstId;
      // 单个商品下总价格
      if (that.data.goodInfo.vipprice && that.data.goodInfo.isvip) {
        addCartInfo.totalProductPrice = that.data.rangeNum * that.data.goodInfo.vipprice;
      } else {
        addCartInfo.totalProductPrice = that.data.rangeNum * that.data.goodInfo.marketprice;
      };
      if (that.data.shopCarList.length > 0) {
        // 如果购物车列表内已存在当前商品，则将列表内的数据进行更新
        that.data.shopCarList.forEach(function (item, index) {
          if (item.productId == addCartInfo.productId) {
            item.count = Number(item.count) + Number(addCartInfo.count);
            // 单个商品下总价格
            if (that.data.goodInfo.vipprice && that.data.goodInfo.isvip) {
              item.totalProductPrice = item.count * item.vipprice;
            } else {
              item.totalProductPrice = item.count * item.marketprice;
            };
          } else {
            that.data.shopCarList.push(addCartInfo);
          }
        });
        that.setData({
          shopCarList: that.data.shopCarList
        });
      } else {
        that.data.shopCarList.push(addCartInfo);
      };
      that.setData({ rangeShow: true });
      that.getRepareList();
    };
    that.getTotal();
  },
  //购物车列表与商品列表做比较
  getRepareList: function () {
    let that = this;
    console.log(that.data.shopCarList);
    if (that.data.shopCarList.length > 0 && that.data.shopCarList) {
      that.data.shopCarList.forEach(function (cart) {
        that.data.navTabList.forEach(function (category) {
          if (category.id == cart.firstId) {
            category.categoryGoodsList.forEach(function(good){
              if(good.id == cart.productId){
                good.count = cart.count
              }
            })
          } else {

          }
        });
      });
    } else {
      that.data.navTabList.forEach(function (category) {
        category.categoryGoodsList.forEach(function(good){
          good.count = 0
        })
      });
    }
    that.setData({
      navTabList: that.data.navTabList,
      cartShow: true,
      shopCarList: that.data.shopCarList,
      goodInfo: '',
      selectRangeId: '0',
      selectRangeName: '',
      rangeNum: '1',
      firstId:'0',
    });

  },
  // 购物车列表显示隐藏
  cartListShowFunction: function () {
    let that = this;
    console.log(that.data.shopCarList);
    if (that.data.cartListShow == 'none') {
      that.setData({
        cartListShow: 'block',
      })
    } else {
      that.setData({
        cartListShow: 'none',
      })
    }
  },
  // 计算总价格和总数量
  getTotal: function () {
    let that = this;
    let shopCarList = that.data.shopCarList;
    console.log(shopCarList);
    let totalCount = 0;
    let totalPrice = 0;
    that.data.shopCarList.forEach(function (item) {
      totalCount = Number(totalCount) + Number(item.count);
      totalPrice = Number(totalPrice) + Number(item.totalProductPrice);
    });
    that.setData({
      totalCount: totalCount,
      totalPrice: totalPrice.toFixed(2),
    });
    if (that.data.shopCarList.length == 0) {
      that.setData({
        cartListShow: 'none',
      });
      setTimeout(function () {
        that.setData({
          cartShow: false
        })
      }, 100);
    }
    that.getRepareList();
  },
  // 购物车列表内加减
  car_jian: function (e) {
    let that = this;
    let shopCarList = that.data.shopCarList;
    let index = e.currentTarget.dataset.index;
    shopCarList[index].count--;
    // shopCarList[index].totalProductPrice = shopCarList[index].productprice * shopCarList[index].count;
    if (shopCarList[index].vipprice) {
      shopCarList[index].totalProductPrice = (shopCarList[index].vipprice * shopCarList[index].count).toFixed(2);
    } else {
      shopCarList[index].totalProductPrice = (shopCarList[index].marketprice * shopCarList[index].count).toFixed(2);
    };
    if (shopCarList[index].count < 1) {
      shopCarList[index].count = 0;
      that.data.niceList.forEach(function (good) {
        if (good.id == shopCarList[index].productId) {
          good.count = 0
        }
      });
      shopCarList.splice(index, 1);
    };
    that.setData({
      shopCarList: shopCarList,
    })
    that.getTotal();
  },
  // 购物车列表内加
  car_jia: function (e) {
    let that = this;
    let shopCarList = that.data.shopCarList;
    let index = e.currentTarget.dataset.index;
    shopCarList[index].count++;
    if (shopCarList[index].vipprice) {
      shopCarList[index].totalProductPrice = (shopCarList[index].vipprice * shopCarList[index].count).toFixed(2);
    } else {
      shopCarList[index].totalProductPrice = (shopCarList[index].marketprice * shopCarList[index].count).toFixed(2);
    };
    that.setData({
      shopCarList: shopCarList,
    })
    that.getTotal();
  },
  // 清空购物车
  clearCarList: function () {
    let that = this;
    that.setData({
      shopCarList: [],
    });
    that.getTotal();
  },
  // 结算
  goSubmit: function () {
    let that = this;
    let shopCarList = that.data.shopCarList;
    console.log(shopCarList);
    let order = {};
    order.cartItems = [];
    shopCarList.forEach(function (item) {
      let submitInfo = {};
      submitInfo.productId = item.productId;
      submitInfo.skuTitle = item.selectRangeName;
      submitInfo.skuId = item.selectRangeId;
      submitInfo.total = 1;
      submitInfo.marketprice = item.marketprice;
      submitInfo.vipprice = item.vipprice;
      order.cartItems.push(submitInfo);
    });
    wx.setStorageSync('order', JSON.stringify(order))
    wx.navigateTo({
      url: '/pages/index/place-order-entity/place-order-entity' +
        '?isSpellgroup=' + '' + '&promoter=' + '' + '&sgorderId=' + ''
        + '&productType=' + that.data.productType + '&cateringType=' + that.data.cateringType
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})